// 加载百度地图SDK
export function loadBaiduMapScript() {
    const baiduMap = document.createElement("script"),
    mapDom = document.createElement('div');
    mapDom.id = 'baidu-map-div'
    document.body.appendChild(mapDom)
    baiduMap.src = `https://api.map.baidu.com/api?v=3.0&ak=QUanOIMwuMM9WZDiXlYV3hts1UBtNRlE&callback=initialize`
    document.body.appendChild(baiduMap)
}

export function initialize() {
    console.log('initialize')
    loadBaiduMapScript.getBaiduMapSdk = 1
}

export function isGetBaiduMapSdk(callback) {
    if (typeof callback === 'function') {
        if (window.BMap) {
            callback()
        } else {
            setTimeout(() => {
                isGetBaiduMapSdk()
            }, 10)
        }
    }
}

// 获取城市名称
export function getCityName(fn){
    if ('loadBaiduMapScript' in getCityName === false) {
        // console.log('loadBaiduMapScript')
        loadBaiduMapScript()
        getCityName.loadBaiduMapScript = 1
    }
    isGetBaiduMapSdk(() => {
        const map = new BMap.Map("baidu-map-div")
        const point = new BMap.Point(116.331398,39.897445)
        map.centerAndZoom(point, 12)
    
        function myFun(result){
            const cityName = result.name
            map.setCenter(cityName)
            if(typeof fn === 'function') fn(cityName)
        }
        const myCity = new BMap.LocalCity()
        myCity.get(myFun)
    })
}